package cn.fz.relaxation.service.impl;

import cn.fz.relaxation.common.model.dto.HotSearchDTO;
import cn.fz.relaxation.common.model.dto.HotSearchDetailDTO;
import cn.fz.relaxation.common.page.Page;
import cn.fz.relaxation.dao.entity.RealxHotSearchDO;
import cn.fz.relaxation.dao.repository.RealxHotSearchRepository;
import cn.fz.relaxation.service.RelaxHotSearchService;
import cn.fz.relaxation.service.convert.HotSearchConvert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static cn.fz.relaxation.cache.hotSearch.HotSearchCacheManager.CACHE_MAP;

@Service
@Slf4j
public class RelaxHotSearchServiceImpl implements RelaxHotSearchService {
    @Autowired
    private RealxHotSearchRepository realxHotSearchRepository;

    /**
     * 保存热搜数据到数据库
     * @param searchDOList List<RealxHotSearchDO>
     * @return Boolean
     */
    @Override
    public Boolean saveCache2DB(List<RealxHotSearchDO> searchDOList) {
        try {
            if (CollectionUtils.isEmpty(searchDOList)){
                return Boolean.TRUE;
            }
            // 查询当前数据是否已经存在
            // 先提取出所有的searchId
            List<String> searchIdList = searchDOList.stream().map(RealxHotSearchDO::getHotSearchId).collect(Collectors.toList());
            // 通过查询searchId获取已经存在的数据
            List<RealxHotSearchDO> list = realxHotSearchRepository.list(
                new QueryWrapper<RealxHotSearchDO>().lambda().in(RealxHotSearchDO::getHotSearchId, searchIdList)
            );
            // 过滤已经存在的数据
            if (CollectionUtils.isNotEmpty(list)){
                // 提取已经存在的id
                List<String> tempIdList = list.stream().map(RealxHotSearchDO::getHotSearchId).collect(Collectors.toList());
                // 和传入的列表里面的id比对,过滤存在的
                searchDOList = searchDOList.stream().filter(item->!tempIdList.contains(item.getHotSearchId())).collect(Collectors.toList());
            }
            // 过滤后再判断还有没有数据
            if (CollectionUtils.isEmpty(searchDOList)){
                return Boolean.TRUE;
            }
            log.info("本次新增[{}]条数据", searchDOList.size());
            // 批量添加
            return realxHotSearchRepository.saveBatch(searchDOList);
        } catch (Exception e) {
            log.error("保存热搜数据到数据库异常", e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public HotSearchDetailDTO queryByType(String type) {
        HotSearchDetailDTO detailDTO = CACHE_MAP.get(type.toUpperCase());
        if (!Objects.isNull(detailDTO)){
            return detailDTO;
        }
        List<RealxHotSearchDO> list = realxHotSearchRepository.lambdaQuery().eq(RealxHotSearchDO::getHotSearchResource, type.toUpperCase())
                .orderByDesc(RealxHotSearchDO::getId).last("limit 51").list();
        if (list.isEmpty()){
            return null;
        }
        return HotSearchDetailDTO.builder()
                // 热搜数据
                .hotSearchDTOList(list.stream().map(HotSearchConvert::toDTOWhenQuery).collect(Collectors.toList()))
                // 更新时间
                .updateTime(Calendar.getInstance().getTime())
                .build();

    }

    @Override
    public Page<HotSearchDTO> pageQueryHotSearchByTitle(String title, Integer pageNum, Integer pageSize) {
        return null;
    }
}
